/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useState, useRef, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Col } from 'antd';
import { useInterval, useUpdateEffect } from 'ahooks';
import NumberDelay from '@/components/NumberDelay';
import CommonBorder from '../../Wrappers/CommonBorder';
import styles from './index.less';

const UpOrDown = ({ rate = 0 }) => (
  <>
    <div className={rate > 0 ? styles.up : styles.down} />
    <div style={{ color: rate > 0 ? '#fb497c' : '#57cf74' }}>
      <NumberDelay number={Math.abs(rate)} /> %
    </div>
  </>
);

/**
 * @description 通用昨日数据组件
 *  */
const ForeLineData = ({
  dispatch,
  branchId,
  isParentFull,
  screenToken,
  currentLevel,
  dispatchType = '',
  title,
  config = [],
}) => {
  const heightRef = useRef({});
  const [height, setHeight] = useState(0);
  const [data, setDate] = useState({});
  const timer = useRef(null);

  const fetchData = useCallback(
    () => {
      dispatch({
        type: dispatchType,
        payload: {
          code: branchId,
          token: screenToken,
          level: currentLevel,
        },
      }).then(res => {
        setDate(res);
      });
    },
    [dispatch, branchId, screenToken, currentLevel],
  );

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);
      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull, heightRef],
  );

  useUpdateEffect(fetchData, [fetchData]);
  useInterval(fetchData, 1000 * 60 * 60);

  return (
    <CommonBorder title={title}>
      <div style={{ height: '100%' }} ref={heightRef}>
        <Row style={{ height }} type="flex" justify="space-between">
          {config.map(val => {
            const { label, key, showPercent } = val;
            const { num, rate } = data[key] || {};
            return (
              <Col key={key} span={24}>
                <Row type="flex" justify="space-between" align="middle" className={styles.content}>
                  <Col>{label}</Col>
                  <Col style={{ flex: 1 }}>
                    <NumberDelay number={num} />
                    {showPercent ? '%' : ''}
                  </Col>
                  <Col>
                    <div className={styles.compare}>
                      <div>今日环比</div>
                      <UpOrDown rate={rate} />
                    </div>
                  </Col>
                </Row>
              </Col>
            );
          })}
        </Row>
      </div>
    </CommonBorder>
  );
};

export default connect(({ chartData, loading, global }, { dispatchType }) => ({
  screenToken: global.screenToken,
  branchId: chartData.currentAreaInfo.branchId,
  currentLevel: chartData.currentAreaInfo.currentLevel,
  loading: loading.effects[dispatchType],
}))(React.memo(ForeLineData));
